
<template>
  <div>
    <!-- 情景定价主页面 -->
    <div v-show="currentPage === 'index'">
      <el-row class="sceneTask container">
        <el-col style="margin-right: 10px" class="content-left">
          <!-- 按钮与搜索 -->
          <el-row class="handleBox">
            <!-- 左侧按钮 -->
            <el-col :span="18">
              <el-button @click="addOrEditFunc('1')">新增</el-button>
              <el-button @click="addOrEditFunc('2')">编辑</el-button>
              <el-button @click="deleFunc()">删除</el-button>
              <el-button @click="addOrEditFunc('3')">复制</el-button>
              <el-button @click="toSiftForm">筛选数据</el-button>
              <el-button @click="toViewData">查看筛选数据</el-button>
              <el-button @click="toExcute()">执行定价</el-button>
              <el-button @click="toMonitor()">执行监控</el-button>
              <el-button @click="refFunc()">执行记录</el-button>
            </el-col>
            <!-- 右侧查询图标 -->
            <el-col :span="6">
              <div class="handleIconBox">
                <!-- 查询弹框 -->
                <el-popover
                  placement="left-start"
                  trigger="click"
                  popper-class="icon_porper"
                >
                  <div class="search_porper">
                    <el-form
                      :model="searchForm"
                      ref="searchForm"
                      label-width="110px"
                      label-position="left"
                      size="mini"
                    >
                      <el-form-item label="情景分析编号：" prop="taskCode">
                        <el-input
                          v-model="searchForm.taskCode"
                          style="width: 150px"
                        ></el-input>
                      </el-form-item>
                      <el-form-item label="开始日期：" prop="startTime">
                        <el-date-picker
                          v-model="searchForm.startTime"
                          type="date"
                          style="width: 150px"
                          value-format="yyyy-MM-dd"
                          placeholder=""
                        ></el-date-picker>
                      </el-form-item>
                    </el-form>
                    <div style="text-align: center; padding: 10px">
                      <el-button size="mini" @click="searchFunc"
                        >查询</el-button
                      >
                      <el-button
                        size="mini"
                        @click="
                          (searchForm.taskCode = ''),
                            (searchForm.startTime = '')
                        "
                        >重置</el-button
                      >
                    </div>
                  </div>
                  <i
                    class="iconfont icon-sousuo"
                    title="搜索"
                    slot="reference"
                  ></i>
                </el-popover>
                <!-- 字段展示弹框 -->
                <el-popover
                  placement="bottom"
                  width="150"
                  trigger="click"
                  popper-class="icon_porper"
                >
                  <div class="operation_checkbox">
                    <el-checkbox-group v-model="checkList">
                      <el-checkbox
                        v-for="item in textData"
                        :label="item.label"
                        :key="item.prop"
                        >{{ item.label }}</el-checkbox
                      >
                    </el-checkbox-group>
                  </div>
                  <i
                    class="iconfont icon-liebiaoshezhi"
                    title="列表设置"
                    slot="reference"
                  ></i>
                </el-popover>
              </div>
            </el-col>
          </el-row>
        </el-col>
      </el-row>
      <!-- 列表 -->
      <el-table
        ref="multipleTable"
        :data="tableData"
        style="width: 100%"
        @row-click="rowClick"
      >
        <el-table-column width="55" type="selection" />
        <el-table-column
          prop="taskCode"
          label="编号"
          show-overflow-tooltip
          v-if="columnState[0]"
        />
        <el-table-column
          prop="taskName"
          label="名称"
          show-overflow-tooltip
          v-if="columnState[1]"
        />
        <el-table-column
          prop="sceneManage.sceneName"
          label="情景"
          show-overflow-tooltip
          v-if="columnState[2]"
        />
        <el-table-column
          prop="taskSd"
          label="开始日期"
          show-overflow-tooltip
          v-if="columnState[3]"
        />
        <el-table-column
          prop="taskEd"
          label="结束日期"
          show-overflow-tooltip
          v-if="columnState[4]"
        />
        <el-table-column
          prop="dataCount"
          label="记录数"
          show-overflow-tooltip
          v-if="columnState[5]"
        />
        <el-table-column
          prop="startTime"
          label="开始时间"
          show-overflow-tooltip
          v-if="columnState[6]"
        />
        <el-table-column
          prop="endTime"
          label="结束时间"
          show-overflow-tooltip
          v-if="columnState[7]"
        />
        <el-table-column
          prop="status"
          label="状态"
          show-overflow-tooltip
          v-if="columnState[8]"
          :formatter="formatRunStatus"
        />
      </el-table>
      <pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="searchForm.page"
        :page-size="searchForm.size"
        @refresh="searchFunc"
        :total="total"
      ></pagination>

      <!-- 新增,编辑 复制保单-->
      <el-dialog
        v-dialogDrag
        :title="titleName"
        :visible.sync="addOrEdit"
        width="514px"
      >
        <el-form
          :model="saveForm"
          ref="saveOrEditRef"
          label-width="110px"
          label-position="left"
          :rules="saveFormRules"
        >
          <el-row>
            <el-col :span="18" :offset="2">
              <el-form-item label="情景分析编号：" prop="taskCode">
                <el-input
                  v-model="saveForm.taskCode"
                  maxlength="40"
                  placeholder="SCENE_"
                  :disabled="operateType == 2"
                  required
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="18" :offset="2">
              <el-form-item label="情景分析名称：" prop="taskName">
                <el-input
                  v-model="saveForm.taskName"
                  maxlength="40"
                  required
                ></el-input>
              </el-form-item>
            </el-col>

            <el-col :span="18" :offset="2">
              <el-form-item label="定价情景：" prop="sceneCode">
                <el-select
                  v-model="saveForm.sceneCode"
                  style="width: 100%"
                  placeholder="请选择"
                >
                  <!-- @change="onChange" -->
                  <el-option
                    v-for="item in sceneOption"
                    :key="item.sceneId"
                    :label="item.sceneName"
                    :value="item.sceneId"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :span="18" :offset="2">
              <el-form-item label="开始日期: " prop="taskSd">
                <el-date-picker
                  v-model="saveForm.taskSd"
                  type="date"
                  style="width: 100%"
                  value-format="yyyy-MM-dd"
                  placeholder=""
                ></el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="18" :offset="2">
              <el-form-item label="结束日期: " prop="taskEd">
                <el-date-picker
                  v-model="saveForm.taskEd"
                  type="date"
                  style="width: 100%"
                  value-format="yyyy-MM-dd"
                  placeholder=""
                ></el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="saveFormButton(operateType)">保 存</el-button>
          <el-button @click="cancelTne" :disabled="!saved">数据筛选</el-button>
          <el-button @click="addOrEdit = false">取 消</el-button>
        </div>
      </el-dialog>
    </div>
    <!-- 数据筛选页面 -->
    <data-filter
      v-if="currentPage === 'dataFilter'"
      @backIndex="backIndex"
      @toFilterData="toFilterData"
      :code="toDataRow.taskCode"
    ></data-filter>
    <!-- 查看筛选数据页面 -->
    <view-filter-data
      v-if="currentPage === 'viewData'"
      :baseData="toDataRow"
      @backIndex="backIndex"
      @toDataFilter="viewToFilter"
    ></view-filter-data>
    <!-- 定价执行监控页面 --------------------------- -->
    <scene-monitor-form
      title="定价执行监控"
      v-if="currentPage === 'monitor'"
      :baseData="toDataRow"
      @backIndex="backIndex"
      @toSubTasks="toSubTasks"
      @toResult="toResult"
    />
    <!-- 执行记录页面 -->
    <excute-notes
      title="定价执行记录"
      v-if="currentPage === 'excuteNotes'"
      :baseData="toDataRow"
      @backIndex="backIndex"
      @toSubTasks="toSubTasks"
    />
    <!-- 定价子任务页面 --------------------------- -->
    <sub-record-form
      title="定价子任务"
      v-if="currentPage === 'subTasks'"
      :baseData="toDataRow"
      @toExcuteNotes="toExcuteNotes"
      @toEngineTask="toEngineTask"
      @backIndex="backIndex"
    />
    <!-- 定价引擎任务页面 --------------------------- -->
    <engine-task
      title="定价引擎任务"
      v-if="currentPage === 'engineTask'"
      :baseData="toDataRow"
      @toExcuteNotes="toExcuteNotes"
      @toSubTasks="toSubTasks"
      @backLast="backLast"
      @toResult="toResult"
    />
    <!-- 情景定价查看结果 -->
    <task-result
      title="情景定价任务结果"
      v-if="currentPage === 'taskResult'"
      :baseData="toDataRow"
      @toBackLast="backLast"
    ></task-result>
  </div>
</template>

<script>
import sceneMonitorForm from "./sceneTask_monitor";
import { pricingTask } from "@/api/index";
import excuteNotes from "./sceneTask_record";
import dataFilter from "./sceneTask_dataFilter";
import viewFilterData from "./sceneTask_viewFilterData";
import subRecordForm from "./sceneTask_subRecord";
import engineTask from "./sceneTask_engineTasks";
import taskResult from "./sceneTask_viewResult";
import moment from "moment";
export default {
  data() {
    return {
      // 当前页面显示
      currentPage: "index",
      comform: "index",
      operateType: "",
      saved: false, // 当前数据是否已保存标识
      // 传入数据筛选和查看数据筛选页面的数据，每个页面需要的数据相似，用一个对象传值
      toDataRow: {},
      //表单字段规则校验
      saveFormRules: {
        taskCode: [
          { required: true, message: "该输入项为必输项", trigger: "blur" },
          {
            pattern: /^(SCENE_[0-9a-zA-Z_]{1,35})$/,
            //     /^(PRICING_[0-9a-zA-Z_]+)$/.test(value.replace(/(^\s*)|(\s*$)/g, "")
            message: "只可输入英文字母、数字和下划线，注：必须以'SCENE_'开头",
            trigger: "blur"
          }
        ],
        taskName: [
          { required: true, message: "该输入项为必输项", trigger: "blur" },
          {
            pattern: /^[\u4E00-\u9FA5A-Za-z0-9（）()\[\]【】{}]{1,40}$/,
            message: "只能输入1-40位的汉字、字母、数字或括号",
            trigger: "blur"
          }
        ],
        sceneCode: [
          { required: true, message: "该输入项为必输项", trigger: "blur" }
        ],
        taskSd: [
          { required: true, message: "该输入项为必输项", trigger: "blur" }
        ],
        taskEd: [
          { required: true, message: "该输入项为必输项", trigger: "blur" }
        ]
      },
      saveForm: {},
      addOrEdit: false,
      titleName: "",
      sceneOption: [],
      total: null,
      searchForm: {
        page: 1,
        size: 15
      },
      tableData: [],
      textData: [
        { prop: "taskCode", label: "编号", disabled: true },
        { prop: "taskName", label: "名称", disabled: true },
        { prop: "scene", label: "情景", disabled: true },
        { prop: "taskSd", label: "开始日期", disabled: true },
        { prop: "taskEd", label: "结束日期", disabled: true },
        { prop: "dataCount", label: "记录数", disabled: true },
        { prop: "startTime", label: "开始时间", disabled: true },
        { prop: "endTime", label: "结束时间", disabled: true },
        { prop: "status", label: "运行状态", disabled: true }
      ],
      checkList: []
    };
  },
  //引入组件
  components: {
    sceneMonitorForm,
    excuteNotes,
    dataFilter,
    viewFilterData,
    subRecordForm,
    engineTask,
    taskResult
  },
  created() {
    console.log(this.$route, "roter");
    // 设置当前页面路由为缓存路由
    if (!this.$route.meta.keepAlive) {
      this.$route.meta.keepAlive = true;
    }
    this.checkListInit();
    this.scene();
    this.searchFunc();
  },

  computed: {
    columnState() {
      let arr = [],
        arr1 = this.textData,
        arr2 = this.checkList;
      for (let i = 0; i < arr1.length; i++) {
        let flag = false;
        for (let j = 0; j < arr2.length; j++) {
          if (arr1[i].label == arr2[j]) {
            flag = true;
            break;
          }
        }
        arr.push(flag);
      }
      return arr;
    }
  },
  mounted() {},
  watch: {},
  methods: {
    // 数据筛选to查看筛选数据
    toFilterData(val) {
      this.currentPage = "viewData";
      this.toDataRow.positionList = val;
    },
    // 返回主页面事件处理
    backIndex(v) {
      this.currentPage = "index";
    },
    // 返回comform
    backLast() {
      this.currentPage = this.comform;
    },
    // 去子任务页面
    toSubTasks(v) {
      if (v) {
        this.toDataRow.pricingCode = v.pricingCode;
      }
      this.currentPage = "subTasks";
    },
    // 跳转到查看结果
    toResult(val) {
      console.log(val, "val");
      this.toDataRow.pricingCode = val.pricingCode;
      this.toDataRow.dataDate = val.dataDate;
      this.comefrom = this.currentPage;
      this.currentPage = "taskResult";
    },
    // 数据筛选查看 to 数据筛选
    viewToFilter() {
      this.currentPage = "dataFilter";
    },
    // 跳去执行记录页面
    toExcuteNotes(val) {
      this.currentPage = "excuteNotes";
    },
    // 跳去引擎任务页面
    toEngineTask(val) {
      if (val) {
        this.toDataRow.pricingCode = val.pricingCode;
        this.toDataRow.dataDate = val.dataDate;
      }
      this.comform = this.currentPage;
      this.currentPage = "engineTask";
    },

    refFunc() {
      let selection = this.$refs.multipleTable.selection;
      if (selection.length != 1) {
        return this.$message.warning("请选择一条数据");
      }
      this.toDataRow = { ...selection[0] };
      this.currentPage = "excuteNotes";
    },
    toMonitor() {
      let selection = this.$refs.multipleTable.selection;
      if (selection.length != 1) {
        return this.$message.warning("请选择一条数据");
      }
      let data = {
        taskCode: selection[0].taskCode
      };
      pricingTask.toMonitorScene(data).then(res => {
        console.log(res, "res");
        if (res.code == 200) {
          let code = selection[0].taskCode;
          let name = selection[0].taskName;
          console.log(code, "code");
          this.toDataRow = {
            taskCode: code,
            taskName: name,
            pricingCode: res.data.pricingRecord.pricingCode,
            taskSd: selection[0].taskSd,
            taskEd: selection[0].taskEd
          };
          this.currentPage = "monitor";
        }
      });
    },
    deleFunc() {
      let selection = this.$refs.multipleTable.selection;
      if (selection.length == 0) {
        return this.$message.warning("请选择要删除的数据");
      }
      let data = [];
      for (let i = 0; i < selection.length; i++) {
        data[i] = selection[i].taskCode;
      }
      console.log(data, "shanchudeshihouchuandideshujv===");
      this.$confirm("你确定要删除选中的数据吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          pricingTask.removeSceneTask(data).then(res => {
            if (res.code == 200) {
              this.$message.success("删除成功");
              this.searchFunc();
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    //执行定价
    toExcute() {
      let selection = this.$refs.multipleTable.selection;
      if (selection.length != 1) {
        return this.$message.warning("请选择一条数据");
      }
      console.log(selection[0]);
      pricingTask
        .sceneTaskExcute({
          taskCode: selection[0].taskCode,
          taskSd:selection[0].taskSd,
          taskEd:selection[0].taskEd,
          sceneCode:selection[0].sceneManage.sceneId
         })
        .then(res => {
          if (res.code == 200 && res.data == "1") {
            this.$message.success("情景定价任务执行成功！");
          } else {
            this.$message.error(res.message);
          }
        });
    },
    // 主页面数据筛选
    toSiftForm() {
      let selection = this.$refs.multipleTable.selection;
      if (selection.length != 1) {
        return this.$message.warning("请选择一条数据");
      }
      let row = selection[0];
      this.toDataRow.taskCode = row.taskCode;
      this.toDataRow.sceneCode = row.sceneManage.sceneCode;
      this.toDataRow.sceneName = row.sceneManage.sceneName;
      this.currentPage = "dataFilter";
    },
    toViewData() {
      let selection = this.$refs.multipleTable.selection;
      if (selection.length != 1) {
        return this.$message.warning("请选择一条数据");
      }
      let row = selection[0];
      this.toDataRow.taskCode = row.taskCode;
      this.toDataRow.sceneCode = row.sceneManage.sceneCode;
      this.toDataRow.sceneName = row.sceneManage.sceneName;
      pricingTask.sceneTaskToViewData("'" + row.taskCode + "'").then(res => {
        if (res.code == 200) {
          this.toDataRow.positionList = res.datas.task.positions;
          this.currentPage = "viewData";
        }
      });
    },
    scene() {
      pricingTask.queryAllEnable().then(res => {
        if (res.code == 200) {
          this.sceneOption = res.datas;
        }
      });
    },
    cancelTne() {
      this.toDataRow = {
        taskCode: this.saveForm.taskCode,
        sceneCode: this.saveForm.sceneCode,
        sceneName: this.$getLabel(
          this.saveForm.sceneCode,
          this.sceneOption,
          "sceneCode",
          "sceneName"
        )
      };
      this.currentPage = "dataFilter";
      this.addOrEdit = false;
    },
    searchFunc() {
      let data = {
        size: this.searchForm.size,
        page: this.searchForm.page,
        taskCode: this.searchForm.taskCode,
        taskSd: this.searchForm.startTime
      };
      pricingTask.findAllSceneTask(data).then(res => {
        if (res.code == 200) {
          this.tableData = res.rows.map(v => {
            let obj = v;
            obj.taskEd = obj.taskEd
              ? moment(obj.taskEd).format("yyyy-MM-DD")
              : "-";
            obj.taskSd = obj.taskSd
              ? moment(obj.taskSd).format("yyyy-MM-DD")
              : "-";
            return obj;
          });
          this.total = res.total;
          //this.tableData.scene = res.rows.sceneManage.sceneName;
        }
      });
    },
    addOrEditFunc(val) {
      if (this.$refs.saveOrEditRef) {
        this.$refs.saveOrEditRef.resetFields();
      }
      this.operateType = val;
      this.saved = false;
      if (val == "2") {
        this.saved = true;
      }
      if (val == 1) {
        this.titleName = "添加情景定价任务";
        this.saveForm = {
          taskCode: "SCENE_"
        };
        this.addOrEdit = true;
      }
      if (val == 2 || val == 3) {
        let selection = this.$refs.multipleTable.selection;
        if (selection.length != 1) {
          return this.$message.warning("请选择一条数据");
        }
        let taskCode = selection[0].taskCode;
        this.titleName = "编辑情景定价任务";
        let data = {
          size: this.searchForm.size,
          page: this.searchForm.page,
          taskCode: taskCode
        };
        console.log(selection[0], "selection");
        this.saveForm = selection[0];
        this.saveForm.sceneCode = selection[0].sceneManage.sceneCode;
        this.addOrEdit = true;
      }
    },
    saveFormButton(operateType) {
      this.$refs.saveOrEditRef.validate(valid => {
        if (valid) {
          console.log(this.saveForm, "dianjibaocundeshihou de ");
          let data = {
            taskCode: this.saveForm.taskCode,
            taskEd: this.saveForm.taskEd,
            taskName: this.saveForm.taskName,
            taskSd: this.saveForm.taskSd,
            sceneManage: {
              sceneId: this.saveForm.sceneCode
            }
          };
          console.log('"' + this.saveForm.taskCode + '"', "code");
          if (operateType == 1 || operateType == 3) {
            pricingTask
              .checkSceneTaskCodeUnique('"' + this.saveForm.taskCode + '"')
              .then(res => {
                if ("0" == res.data) {
                  pricingTask.saveSceneTask(data).then(res => {
                    this.$message({
                      message: "保存成功",
                      type: "success"
                    });
                    this.saved = true;
                    this.searchFunc();
                  });
                } else {
                  this.$message({
                    message: "此编码已存在",
                    type: "warning"
                  });
                }
              });
          } else {
            pricingTask.saveSceneTask(data).then(res => {
              this.$message({
                message: "保存成功",
                type: "success"
              });
              this.saved = true;
              this.searchFunc();
            });
          }
        }
      });
    },
    rowClick(row) {
      if (this.$refs.multipleTable) {
        this.$refs.multipleTable.clearSelection();
      }
      this.$refs.multipleTable.toggleRowSelection(row, true);
    },
    checkListInit() {
      this.checkList = this.textData.map(v => {
        return v.label;
      });
    },
    formatRunStatus(row, column) {
      if (row.status == "INIT") {
        return "初始化";
      } else if (row.status == "PREPARING") {
        return "准备中";
      } else if (row.status == "RUNNING") {
        return "运行中";
      } else if (row.status == "FINISH") {
        return "已完成";
      } else if (row.status == "ERROR") {
        return "错误";
      } else if (row.status == "SENDBACK") {
        return "已退回";
      } else if (row.status == "RETRY") {
        return "再次尝试中";
      } else {
        return "";
      }
    },
    handleSizeChange(val) {
      this.searchForm.size = val;
      this.searchFunc();
      console.log(val, "每页数");
    },
    handleCurrentChange(val) {
      this.searchForm.page = val;
      this.searchFunc();
      console.log(val, "当前页");
    }
  }
};
</script>
<style lang="scss" scoped>
/deep/ .formTitle {
  font-size: 14px;
  font-weight: 700;
  display: block;
  margin-bottom: 10px;
}
</style>